package data_api

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"giv-vue-blog/models/res"
)

type DataSumResponse struct {
	UserCount       int `json:"user_count"`
	ArticleCount    int `json:"article_count"`
	MessageCount    int `json:"message_count"`
	ChatGroupCount  int `json:"chat_group_count"`
	TodayLoginCount int `json:"today_login_count"`
	TodaySignCount  int `json:"today_sign_count"`
}

// DataSumView 统计用户、文章、消息、群聊以及今日登录和注册次数
// @Summary 统计用户、文章、消息、群聊以及今日登录和注册次数
// @Tags 数据管理
// @Accept json
// @Produce json
// @Success 200 {string} json "{"code": 0, "message": "请求成功", "data": DataSumResponse}"
// @Failure 500 {string} json "{"code": 2, "message": "服务器内部错误"}"
// @Router /api/digg_count [get]
func (DataApi) DataSumView(c *gin.Context) {
	var userCount, articleCount, messageCount, ChatGroupCount int
	var todayLoginCount, todaySignCount int
	result, _ := global.EsClient.
		Search(models.ArticleModel{}.Index()).
		Query(elastic.NewMatchAllQuery()).
		Do(context.Background())
	//统计索引个数
	articleCount = int(result.Hits.TotalHits.Value)                                            //文章个数
	global.DB.Model(models.UserModel{}).Select("count(id)").Scan(&userCount)                   //用户个数
	global.DB.Model(models.MessageModel{}).Select("count(id)").Scan(&messageCount)             //消息个数
	global.DB.Model(models.ChatModel{IsGroup: true}).Select("count(id)").Scan(&ChatGroupCount) //群聊个数
	global.DB.Model(models.LoginDataModel{}).
		Where("to_days(created_at)=to_days(now())").
		Select("count(id)").
		Scan(&todayLoginCount) //今日登录次数
	global.DB.Model(models.UserModel{}).
		Where("to_days(created_at)=to_days(now())").
		Select("count(id)").
		Scan(&todaySignCount) //今日注册次数
	//返回构造的对应数据
	res.OkWithData(DataSumResponse{
		UserCount:       userCount,
		MessageCount:    messageCount,
		ChatGroupCount:  ChatGroupCount,
		ArticleCount:    articleCount,
		TodayLoginCount: todayLoginCount,
		TodaySignCount:  todaySignCount,
	}, c)
}
